package com.cherry.androidcode.util

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import com.cherry.androidcode.MainApp
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import java.io.ByteArrayOutputStream
import java.util.*
import kotlin.math.roundToInt

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 2019/6/7
 */

fun Boolean.toInt(): Int = if (this) 1 else 0


fun Int.resToColor(): Int = ResourcesCompat.getColor(getResource(), this, null)

fun Int.resToDp(): Int = getResource().getDimensionPixelSize(this)

fun Int.resToDrawable(): Drawable = ResourcesCompat.getDrawable(getResource(), this, null)!!

fun Int.resToString(): String = getResource().getString(this)

fun Int.resToString(vararg argument: Any): String = getResource().getString(this, *argument)

fun Int.resToStringArray(): Array<String> = getResource().getStringArray(this)

fun Float.dpToPxF(): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, getResource().displayMetrics)
fun Float.dpToPx(): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, getResource().displayMetrics).roundToInt()

fun Float.spToPxF(): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this, getResource().displayMetrics)
fun Float.spToPx(): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this, getResource().displayMetrics).roundToInt()

//example :val turns = Gson().fromJson<Turns>(pref.turns)
inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)

fun <T : View> Fragment.findViewById(@IdRes id: Int) = this.view?.findViewById<T>(id)!!

fun Activity.hideKeyBoard() {
    val inputMethodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(this.window.decorView.windowToken, 0)
}

@JvmOverloads
fun Int.inflate(viewGroup: ViewGroup? = null, attachView: Boolean = false, context: Context = MainApp.CONTEXT): View = LayoutInflater.from(context).inflate(this, viewGroup, attachView)

fun TextView.getText() = this.text.toString()
fun TextView.getTextTrim() = this.text.toString().trim()
fun TextView.isEmpty() = TextUtils.isEmpty(this.text.toString().trim())

fun View.setVisible() {
    this.visibility = View.VISIBLE
}

fun View.setInVisible() {
    this.visibility = View.INVISIBLE
}

fun View.setGone() {
    this.visibility = View.GONE
}


fun View.setOnSingleClickListener(limitTime: Long = 500L, onSingleClick: (View) -> Unit) {
    val lastClickTime = if (this.tag != null) this.tag as Long else 0L
    val currentTime = Calendar.getInstance().timeInMillis
    if (currentTime - lastClickTime > limitTime) {//过滤掉限制时间内的连续点击
        this.setTag(this.id, currentTime)
        this.setOnClickListener { onSingleClick(it) }
    }
}


/**
 * 这里针对MMKV保存ArrayList和枚举做一个封装
 */
fun <T> MMKV.encode(key: String, t: T) {
    encode(key, GlobalGson.toJson(t))
}

fun <T> MMKV.decodeList(key: String): List<T> = GlobalGson.fromJson<List<T>>(decodeString(key)
        ?: emptyList<T>().toString())

inline fun <reified T> MMKV.decodeEnum(key: String): T? {
    val decodeString = decodeString(key)
    return if (decodeString != null) {
        GlobalGson.fromJson(decodeString, T::class.java)
    } else {
        null
    }
}

inline fun <reified T> MMKV.decodeEnum(key: String, def: T) = decodeEnum(key) ?: def


fun Bitmap.bitmap2ByteArray() = ByteArrayOutputStream().let {
    this.compress(Bitmap.CompressFormat.PNG, 100, it)
    it.toByteArray()
}

fun String.getALiParams(key: String): String? = substring(key.length).removeBrackets()

fun String.removeBrackets(): String? = if (!TextUtils.isEmpty(this)) {
    var string = this
    if (startsWith("\"")) {
        string = replaceFirst("\"".toRegex(), "")
    }
    if (endsWith("\"")) {
        string = substring(0, length - 1)
    }
    string
} else {
    this
}